package cc.sunwl.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import cc.sunwl.security.service.UserService;

@SuppressWarnings("deprecation")
@Configuration
@EnableWebSecurity
// 启用Security注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserService userService;

	/**
	 * configure(HttpSecurity http) 方法<br>
	 * <p>
	 * 通过 authorizeRequests() 定义哪些URL需要被保护、哪些不需要被保护。例如以上代码指定了 / 和 /home
	 * 不需要任何认证就可以访问，其他的路径都必须通过身份验证
	 * </p>
	 * <p>
	 * 通过 formLogin() 定义当需要用户登录时候，转到的登录页面
	 * </p>
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http//
				.authorizeRequests()//
				.antMatchers("/", "/home").permitAll()//
				.anyRequest().authenticated()//
				.and()//
				.formLogin()//
				.loginPage("/login")//
				.permitAll()//
				.and()//
				.logout()//
				.permitAll();
		// 关闭csrf 防止循环定向
		// http.csrf().disable();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		ReflectionSaltSource rss = new ReflectionSaltSource();
		rss.setUserPropertyToUse("username");
		DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
		provider.setSaltSource(rss);
		provider.setUserDetailsService(this.userService);
		provider.setPasswordEncoder(passwordEncoder());
		auth.authenticationProvider(provider);
		// auth.userDetailsService(this.userService);
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
		return md5PasswordEncoder;
	}

}
